
import { inject, observer } from 'mobx-react';
import { observable } from 'mobx';

import { Modal, Steps, Button, Form, Tabs, Row, Col, Tree, Pagination, Switch } from "antd";
import { WeaInput, WeaTextarea, WeaNewScroll, WeaInputSearch, WeaCheckbox } from 'ecCom';
import { STEP_CHANGED, STEP_FINISHED } from '../../../constants/appCreate';

import QueueAnim from 'rc-queue-anim';
import AppSkinList from "./AppSkinList";

const Step = Steps.Step;
const ButtonGroup = Button.Group;
const FormItem  = Form.Item;
const TabPane = Tabs.TabPane;
const TreeNode = Tree.TreeNode;

@inject('appCreateStore')
@observer
export default class AppCreate extends React.Component {
    componentDidMount() {
        const { appCreateStore } = this.props;
        const { getAppList, selectApp, selectMode } = appCreateStore;

        getAppList().then(selectApp).then(selectMode);
    }

    next() {
        const { appCreateStore } = this.props;
        const { stepStatusChange, validateAppForm, stepChange, currentStep } = appCreateStore;

        if (currentStep == 0) {
            stepStatusChange(STEP_CHANGED);
            return validateAppForm(true);
        }
        stepChange(currentStep + 1);
    }

    createApp() {
        const { appCreateStore, onClosed, closeAppCreate } = this.props;
        const { saveApp, resetStore, currentStep, stepStatusChange, validateAppForm } = appCreateStore;

        if (currentStep == 0) {
            stepStatusChange(STEP_FINISHED);
            return validateAppForm(true);
        }
        saveApp().then((data) => {
            onClosed(data.appid);
            closeAppCreate();
            resetStore();
        });
    }

    stepStatusChange() {
        const { appCreateStore, onClosed, closeAppCreate } = this.props;
        const { stepStatus, stepChange, saveApp, resetStore, isCreating } = appCreateStore;
        
        if(stepStatus == STEP_CHANGED) {
            stepChange(1);
        } else if(stepStatus == STEP_FINISHED) {
            if(isCreating) return;

            saveApp().then(() => {
                onClosed();
                closeAppCreate();
                resetStore();
            });
        }
    }

    closeAppCreate() {
        const { closeAppCreate, appCreateStore } = this.props;
        const { resetStore } = appCreateStore;

        closeAppCreate();
        resetStore();
    }

    render() {
        const { appCreateStore, visible } = this.props;
        const { currentStep, isCreating, isValidateAppForm, applist, appid, modelist, modeid, modelayout, qualifiedModes, currentPage, pageSize } = appCreateStore;
        const { stepChange, validateAppForm, setAppBaseInfo, selectApp, searchMode, currentPageChange, modelayoutChange, selectMode, selectSkin } = appCreateStore;
        const steps = [
            { key: 0, title: "基本信息", description: "填写应用的基本信息" },
            { key: 1, title: "添加模块", description: "选择添加表单建模中的模块" },
            { key: 2, title: "选择皮肤", description: "为应用选择一款皮肤" }
        ];
        const footer = (
            <ButtonGroup>
                <Button type="primary" loading={isCreating} onClick={this.createApp.bind(this)}>直接完成</Button>
                {currentStep > 0 && currentStep <= 2 ? <Button type="ghost" onClick={() => stepChange(currentStep - 1)}>上一步</Button> : null}
                {currentStep < 2 ? <Button type="ghost" onClick={this.next.bind(this)}>下一步</Button> : null}
            </ButtonGroup>
        );
        const loop = applist => applist.map((app, index) => {
            if (app.children) {
                return (
                    <TreeNode key={String(app.id)} title={app.name}>
                        {loop(app.children)}
                    </TreeNode>
                )
            }
            return <TreeNode key={String(app.id)} title={app.name}></TreeNode>
        });
        const currModes = qualifiedModes.map(mode => { // 当前页的mode
            return (
                <li key={mode.id} className={modeid == mode.id ? "active" : ""} onClick={() => selectMode(appid, mode.id)}>
                    <p>{mode.entityname}</p>
                    <span>{mode.entitydesc}</span>
                </li>
            );
        }).slice(pageSize * (currentPage - 1), pageSize * currentPage);
        
        return (
            <Modal
                title="创建应用"
                width="800"
                wrapClassName="app-create"
                bodyStyle={{ padding: "16px 0" }}
                visible={visible}
                footer={footer}
                onCancel={this.closeAppCreate.bind(this)}>
                <Steps current={currentStep} style={{ padding: "0 16px 16px" }}>
                    {
                        steps.map(step => {
                            return <Step key={step.key} title={step.title} description={step.description}></Step>
                        })
                    }
                </Steps>
                <div style={{ height: "516px" }}>
                    <Tabs activeKey={String(currentStep)}>
                        <TabPane tab="" key="0">
                            <AppInfoForm
                                validate={isValidateAppForm}
                                closeValidate={() => validateAppForm(false)}
                                onValid={this.stepStatusChange.bind(this)}
                                onFieldChange={setAppBaseInfo}></AppInfoForm>
                        </TabPane>
                        <TabPane tab="" key="1">
                            <Row style={{ padding: "0 16px" }}>
                                <Col span={7} style={{ paddingRight: "5px" }}>
                                    <WeaNewScroll scrollId="applist" height="510">
                                        {applist.length ?
                                            <Tree
                                                onSelect={keys => selectApp(keys[0]).then(selectMode)}
                                                defaultExpandedKeys={[String(applist[0].id)]}
                                                selectedKeys={[String(appid)]}>
                                                {loop(applist)}
                                            </Tree> : null
                                        }
                                    </WeaNewScroll>
                                </Col>
                                <Col span={7} style={{ textAlign: "center" }}>
                                    <WeaInputSearch placeholder="输入模块名称" style={{ width: "100%" }} onSearchChange={searchMode}></WeaInputSearch>
                                    {modelist.length ?
                                        <div>
                                            <ul className="appmode-list"> 
                                                { currModes }
                                            </ul>
                                            <Pagination
                                                onChange={currentPageChange}
                                                size="small"
                                                current={currentPage}
                                                pageSize={pageSize}
                                                total={qualifiedModes.length}
                                                style={{ display: "inline-block" }}>
                                            </Pagination>
                                        </div>
                                        :
                                        <div style={{ padding: "20px 12px", color: "#666" }}>无匹配结果显示</div>
                                    }
                                </Col>
                                <Col span={10} style={{ paddingLeft: "5px" }}>
                                    {modelayout ?
                                        <ModelLayout
                                            appmodelayout={modelayout}
                                            onChange={modelayoutChange}>
                                        </ModelLayout> : null
                                    }
                                </Col>
                            </Row>
                        </TabPane>
                        <TabPane tab="" key="2">
                            <div style={{ paddingLeft: "25px", background: "#eee" }}>
                                <WeaNewScroll scrollId="skinlist" height="500">
                                    <AppSkinList onSelect={selectSkin} height="270px"></AppSkinList>
                                </WeaNewScroll>
                            </div>
                        </TabPane>
                    </Tabs>
                </div>
            </Modal>
        );
    }
}

class AppInfoForm extends React.Component {
    componentDidMount() {
        setTimeout(this.nameInputFocus.bind(this));
    }

    nameInputFocus() {
        $(this.nameInputCon).find("input:visible").select().focus();
    }

    render() {
        const { nameInputFocus, props } = this;
        const { validate, closeValidate, onValid, form } = props;
        const { getFieldProps, validateFields } = form;
        const formItemLayout = {
            labelCol: { span: 7 },
            wrapperCol: { span: 14 },
        };

        const nameProps = getFieldProps("appname", {
            rules: [{
                required: true,
                message: "请输入应用名称"
            }]
        });

        if (validate) {
            validateFields(["appname"], (errors, values) => {
                closeValidate();

                if (!errors) return onValid();

                setTimeout(nameInputFocus.bind(this));
            })
        }

        return (
            <Form horizontal style={{ width: "80%", margin: "0 auto", paddingTop: "30px" }} >
                <div ref={el => { this.nameInputCon = el }}>
                    <FormItem
                        {...formItemLayout}
                        label="名称">
                        <WeaInput {...nameProps} placeholder="请输入应用名称" />
                    </FormItem>
                </div>
                <FormItem
                    {...formItemLayout}
                    label="行业">
                    <WeaInput {...getFieldProps("industry") } />
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="发布">
                    <Switch defaultChecked={true} {...getFieldProps("ispublish")} />
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="描述">
                    <WeaInput type="textarea" {...getFieldProps("descriptions") } style={{ padding: 0 }} />
                </FormItem>
            </Form>
        );
    }
}

AppInfoForm = Form.create({
    onFieldsChange: (props, fields) => {
        const { onFieldChange } = props;
        let fieldsInfo = {};

        Object.keys(fields).forEach(key => {
            fieldsInfo[key] = fields[key].value;
        });
        onFieldChange(fieldsInfo);
    }
})(AppInfoForm);

const defaultTypes = ["显示布局", "新建布局", "编辑布局"];
const layoutMapping = {
    addLayout: {
        layoutname: "新建布局",
        iconsrc: "/mobilemode/images/circle_add_wev8.png",
    },
    editLayout: {
        layoutname: "编辑布局",
        iconsrc: "/mobilemode/images/circle_edit_wev8.png",
    },
    showLayout: {
        layoutname: "显示布局",
        iconsrc: "/mobilemode/images/circle_view_wev8.png"
    }
};

@observer class ModelLayout extends React.Component {
    @observable layoutKey = "homepageLayout";
    @observable searchLayoutKey = "homepageSearchLayout";

    constructor() {
        super();
        this.normalSelect = this.normalSelect.bind(this);
        this.otherSelect = this.otherSelect.bind(this);
        this.checkAll = this.checkAll.bind(this);
    }

    normalSelect(tabType, layoutType) {
        const { appmodelayout, onChange } = this.props;
        const isexist = Math.abs(appmodelayout[tabType][layoutType] - 1);

        appmodelayout[tabType][layoutType] = isexist;
        onChange(appmodelayout, isexist == 1 ? 1 : -1);
    }

    otherSelect(tabType, index) {
        const { appmodelayout, onChange } = this.props;
        let isexist = false;

        if (tabType == "homepageLayout") {
            isexist = Math.abs(appmodelayout[tabType]["otherLayout"][index].exist - 1);
            appmodelayout[tabType]["otherLayout"][index].exist = isexist;
        } else {
            isexist = Math.abs(appmodelayout[tabType][index].exist - 1);
            appmodelayout[tabType][index].exist = isexist;
        }
        onChange(appmodelayout, isexist == 1 ? 1 : -1);
    }

    checkAll(ischecked, layoutType) {
        ischecked = +ischecked;
        let { appmodelayout, onChange } =  this.props;
        let exp = 0;
        let flag = ischecked ? 1 : -1;

        switch(layoutType) {
            case 'homepageLayout':
                let { homepageLayout } = appmodelayout;
                Object.keys(homepageLayout).forEach(type => {
                    let val = homepageLayout[type];
                    if(type != "otherLayout") {
                        exp += val == ischecked ? 0 : flag;
                        return homepageLayout[type] = ischecked;
                    }
                    val.forEach(mode => {
                        exp += mode.exist == ischecked ? 0 : flag
                        mode.exist = ischecked;
                    });
                });
                break;
            case 'modelayout':
                let { modelayout } = appmodelayout;
                Object.keys(modelayout).forEach(type => {
                    let val = modelayout[type];
                    exp += val == ischecked ? 0 : flag;
                    modelayout[type] = ischecked;
                });
                break;
            case 'homepageSearchLayout':
            case 'modeSearchLayout':
                let searchLayout = appmodelayout[layoutType];
                searchLayout.forEach(mode => {
                    exp += mode.exist == ischecked ? 0 : flag;
                    mode.exist = ischecked;
                });
                break;
        }
        onChange(appmodelayout, exp);
    }

    layoutKeyChange(key) {
        this.layoutKey = key;
        this.searchLayoutKey = this.layoutKey == "modelayout" ? "modeSearchLayout" : "homepageSearchLayout";
    }

    searchLayoutKeyChange(key) {
        this.searchLayoutKey = key;
    }

    render() {
        const { normalSelect, otherSelect, layoutKey, searchLayoutKey } = this;
        let { appmodelayout } = this.props;
        const { homepageLayout, homepageSearchLayout, modelayout, modeSearchLayout, moduleName } = appmodelayout;
        const normalLayoutCard = (tabType, layoutType, isdefault) => {
            let layout = layoutMapping[layoutType];

            if (layoutType == "otherLayout") return null;

            let isexist = appmodelayout[tabType][layoutType];
            let className = "ml-card" + (isdefault ? " default" : "") + (isexist == 1 ? " selected" : "");
            
            return (
                <div onClick={() => normalSelect(tabType, layoutType)} className={className} data-tag={isdefault ? "默认" : ""}>
                    <img src={layout.iconsrc} />
                    <div>
                        <p>{layout.layoutname}</p>
                        <span>{moduleName}</span>
                    </div>
                    <div data-checked="√" className="card-checked"></div>
                </div>
            );
        };
        const otherLayoutCard = (tabType, layout, index) => {
            const isexist = layout.exist;
            const version = layout.version;
            let tag = "";

            if(version == 2) {
                tag = "excel布局";
            } else if(version == 3) {
                tag = "html布局";
            }

            const className = "ml-card" + (isexist ? " selected" : "") + (tag ? " normal" : "");

            return (
                <div data-tag={tag} onClick={() => otherSelect(tabType, index)} className={className}>
                    <img src={layout.iconsrc || "/mobilemode/images/circle_list_wev8.png"} />
                    <div>
                        <p>{layout.layoutname || layout.customname || moduleName}</p>
                        <span>{defaultTypes[layout.type] || moduleName}</span>
                    </div>
                    <div data-checked="√" className="card-checked"></div>
                </div>
            )
        };
        
        return (
            <div className="model-layout">
                <Tabs activeKey={layoutKey} onChange={this.layoutKeyChange.bind(this)}>
                    <TabPane tab="自定义页面布局" key="homepageLayout">
                        <div className="check-all" key="3">
                            <span>全选</span>
                            <WeaCheckbox onChange={ischekced => this.checkAll(ischekced, layoutKey)}></WeaCheckbox>
                        </div>
                        <WeaNewScroll scrollId="homepageLayoutScroll" height="235">
                            {homepageLayout ?
                                Object.keys(homepageLayout).map(function (type) {
                                    return normalLayoutCard("homepageLayout", type, true);
                                }) : null}
                            {homepageLayout && homepageLayout.otherLayout.length ?
                                homepageLayout.otherLayout.map((layout, index) => otherLayoutCard("homepageLayout", layout, index)) : null}
                        </WeaNewScroll>
                    </TabPane>
                    <TabPane tab="模块布局" key="modelayout">
                        <div className="check-all" key="3">
                            <span>全选</span>
                            <WeaCheckbox onChange={ischekced => this.checkAll(ischekced, layoutKey)}></WeaCheckbox>
                        </div>
                        <WeaNewScroll scrollId="homepageLayoutScroll" height="235">
                            {modelayout ?
                                Object.keys(modelayout).map(type => normalLayoutCard("modelayout", type)) : null}
                        </WeaNewScroll>
                    </TabPane>
                </Tabs>
                <Tabs activeKey={searchLayoutKey} onChange={this.searchLayoutKeyChange.bind(this)}>
                    <TabPane tab="自定义页面查询" key="homepageSearchLayout">
                        {homepageSearchLayout ?
                            homepageSearchLayout.map((layout, index) => otherLayoutCard("homepageSearchLayout", layout, index)) : null}
                    </TabPane>
                    <TabPane tab="模块查询" key="modeSearchLayout">
                        {modeSearchLayout ?
                            modeSearchLayout.map((layout, index) => otherLayoutCard("modeSearchLayout", layout, index)) : null}
                    </TabPane>
                    <div className="check-all" key="3">
                        <span>全选</span>
                        <WeaCheckbox onChange={ischekced => this.checkAll(ischekced, searchLayoutKey)}></WeaCheckbox>
                    </div>
                </Tabs>
            </div>
        );
    }
}